<template>
  <div class="container">
    <div class="audio-item first-item flex-center">
      <div class="num">序号</div>
      <!-- <div class="title">标题</div> -->
      <div class="audio">音频</div>
      <div class="playbtn"></div>
      <div class="trans">操作</div>
    </div>
    <div
      v-for="(item, index) in urlArray"
      :class="'demo-' + index"
      :key="index"
      class="audio-item flex-center"
    >
      <div class="num">{{ item.id }}</div>
      <!-- <div class="title">{{ item.fileId }}</div> -->
      <vue-audio-native
        class="audio"
        size="default"
        :url="item.fileUrl"
        :showCurrentTime="showCurrentTime"
        :showControls="showControls"
        :showVolume="showVolume"
        :showDownload="showDownload"
        :autoplay="autoplay"
        :hint="hint"
        :waitBuffer="waitBuffer"
        :downloadName="downloadName"
        @on-change="change"
        @on-timeupdate="timeupdate"
        @on-metadata="metadata"
        @on-audioId="audioId"
        @on-end="end"
      >
      </vue-audio-native>
      <div
        class="playbtn"
        :style="{
          backgroundImage: `url(${
            choosedId == item.id ? playBtnZT : playBtnBF
          })`,
        }"
        @click="togglePlayBtn(item)"
      ></div>
      <div class="trans">
        <el-button type="primary" size="mini" @click="transformAudio(item)"
          >转写</el-button
        >
      </div>
    </div>
    <el-pagination
      v-if="urlArray.length > 0"
      background
      layout="prev, pager, next"
      :current-page="currentPage"
      :page-size="pagesize"
      :total="allAudio.length"
      @current-change="handleCurrentChange"
    >
    </el-pagination>

    <el-dialog title="转写翻译" :visible.sync="dialogVisible">
      <div class="text-wrap">
        <div class="tit">语音已转文字</div>
        <div class="text">{{ transText }}</div>
        <template>
          <el-button
            v-if="language !== 'chin'"
            type="primary"
            style="margin-top: 20px"
            @click="fanyi"
            >翻译</el-button
          >
          <div class="text" v-if="language !== 'chin'">{{ fanyiText }}</div>
        </template>
      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false"
          >确 定</el-button
        >
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { audioService, baseService } from "@/utils/configHttp";
export default {
  data() {
    return {
      allAudio: [],
      currentPage: 0,
      pagesize: 10,
      urlArray: [
        // require("../assets/222.mp3"),
      ],
      choosedId: null,
      lastChoosedId: null,
      language: "",
      transText: "",
      fanyiText: "",
      currentFileId: "",
      // url: require("../assets/222.mp3"),
      playBtnZT: require("@/assets/images/zanting.svg"),
      playBtnBF: require("@/assets/images/bofang.svg"),
      showCurrentTime: true, //默认true，是否显示当前播放时间
      showControls: false, //默认false，true:展示原生音频播放控制条，false：展示模拟播放控制条
      showVolume: true, //默认true，默认显示音量调节和静音按钮 true显示音量调节和静音按钮
      showDownload: false, //默认true，默认显示下载按钮
      autoplay: false, //默认false，自动播放有效音频(由于高版本浏览器协议限制，初始化页面时无法自动播放，可以在点击页面后手动触发)
      waitBuffer: true, //默认true，拖拽到未加载的时间，是否需要等待加载，true:滑块位置不动，等待加载音频资源后播放，false：当滑动位置大于当前缓冲的最大位置，则重置到当前最大缓冲位置
      downloadName: "下载音频", //默认“下载音频”，在Chrome和火狐、同域名下，修改下载文件名称，其它保持原文件服务器名称
      hint: "音频正在加载中，请稍等…", //无音频情况下提示文案
      currentAudioId: [], //当前正在播放的audio id数组

      dialogVisible: false,
    };
  },
  created() {
    this.queryAudioList();
  },
  mounted() {
    // setTimeout(() => {
    //   this.urlArray = [require("../assets/222.mp3")];
    // }, 3000);
  },
  methods: {
    togglePlayBtn(item) {
      if (this.currentAudioId.length == 0) {
        return false;
      }
      this.choosedId = item.id;
      let index = Number(item.id) % this.pagesize;
      if (index == 0) index = 10;
      index = index - 1;
      if (this.lastChoosedId == item.id) {
        document.getElementById(this.currentAudioId[index]).pause();
        this.lastChoosedId = null;
        this.choosedId = null;
        return false;
      }
      this.currentAudioId.forEach((key, i) => {
        if (i == index) {
          document.getElementById(this.currentAudioId[i]).play();
          this.lastChoosedId = item.id;
        } else {
          document.getElementById(this.currentAudioId[i]).pause();
        }
      });
    },
    handleCurrentChange: function (currentPage) {
      this.choosedId = null;
      this.currentPage = currentPage;
      if (currentPage > 1) {
        this.urlArray = this.allAudio.slice(
          (currentPage - 1) * this.pagesize,
          currentPage * this.pagesize
        );
      } else if (currentPage == 1) {
        this.urlArray = this.allAudio.slice(0, this.pagesize);
      }
    },
    queryAudioList() {
      baseService
        .get("/audio/audioList")
        .then((res) => {
          this.allAudio = res;
          this.urlArray = res.slice(0, this.pagesize);
        })
        .catch((err) => {
          alert(err.msg);
        });
    },
    transformAudio(item) {
      this.transText = "";
      this.language = "";
      this.fanyiText = "";
      this.currentFileId = item.fileId;
      // 科大讯飞语音转写接口
      // export function sdScopes(data) {
      //     return http.get('/data_screen/sd/sdScopes',{ params: {data} })
      // }
      this.dialogVisible = true;
      try {
        audioService
          .post("/audio/langDetectTrans", {
            fileId: item.fileId,
            uri: item.fileUrl,
            encoding: 0,
          })
          .then((res) => {
            this.transText = res.body.target;
            this.language = res.body.lang;
          })
          .catch((err) => {
            alert(err.msg);
          });
      } catch (err) {
        console.log("error", err);
        alert("转写错误！");
      }
    },
    fanyi() {
      audioService
        .post("/text/trans", {
          fileId: this.currentFileId,
          content: this.transText,
          type: "zacn",
        })
        .then((res) => {
          console.log(1010101, res);
          this.fanyiText = res.body.target;
        })
        .catch((err) => {
          alert(err.msg);
        });
    },
    change(event) {
      // if (event == true && typeof event == "boolean") {
      //   console.log(9090, typeof event, this.currentAudioId);
      //   this.currentAudioId.forEach((item) => {
      //     document.getElementById(item).pause();
      //   });
      // }
      console.log("当前播放状态：", event);
    },
    timeupdate(event) {
      console.log("当前播放时间：", event);
    },
    metadata(event) {
      console.log(event, "音频长度：", event.target.duration);
    },
    //切换音频地址
    swtichSrc(index) {
      let t = this;
      t.url = t.urlArray[index];
    },
    //获取渲染能够播放音频currentAudioId，可存全局，用以播放和暂停音频
    audioId(event) {
      console.log(event, 9999999);
      if (this.currentAudioId.length >= this.pagesize) {
        this.currentAudioId.shift();
      }
      this.currentAudioId.push(event);
    },
    //获取到音频停止的事件，true为
    end(event) {
      if (event == true) {
        this.choosedId = null;
      }
      console.log(event, 281789);
    },
    //通过音频列表的下标获取渲染能够播放音频currentAudioId即组件的id，并使用组件的id，用来开始播放录音
    play(index) {
      document.getElementById(this.currentAudioId[index]).play();
    },
    //通过音频列表的下标获取渲染能够播放音频currentAudioId即组件的id，并使用组件的id，，用来暂停播放录音
    pause(index) {
      document.getElementById(this.currentAudioId[index]).pause();
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  color: #ffffff;
  margin: 30px;
  padding: 20px;
  background: #0e1f61;
  .audio-item {
    &.first-item {
      color: #00d8f5;
    }
    height: 0.6rem;
    &:nth-child(2n + 1) {
      background: linear-gradient(
        90deg,
        rgba(14, 40, 106, 0.5) 0%,
        #0e286a 50%,
        rgba(14, 40, 106, 0.5) 100%
      );
    }
  }
  .num {
    width: 1.4rem;
  }
  .title {
    width: 4rem;
  }
  .playbtn {
    width: 0.8rem;
    height: 0.6rem;
    background-repeat: no-repeat;
    background-position: center;
    background-size: 0.4rem 0.4rem;
  }
  .trans {
    margin-left: 20px;
    width: 2rem;
  }
  ::v-deep .audio {
    position: relative;
    // 旋转
    .audio-left {
      span {
        color: #ffffff;
      }
      .iconfont {
        display: none;
      }
    }
    width: 6rem;
    .played {
      position: absolute;
      right: -30px;
      margin-right: 10px;
    }
  }
}
.text-wrap {
  .tit {
    // text-align: left;
    font-size: 20px;
    font-weight: 500;
    color: #00d8f5;
    line-height: 24px;
  }
  .text {
    max-height: 2rem;
    overflow-y: scroll;
    margin-top: 20px;
    padding: 20px 10px;
    text-align: justify;
    font-size: 16px;
    font-weight: 400;
    color: #00d8f5;
    line-height: 24px;
    border-radius: 2px;
    border: 1px solid #00d8f5;
    border-radius: 6px;
  }
}
</style>
<style lang="scss">
.hint {
  color: white !important;
}
.el-pagination {
  margin-top: 16px;
}
.el-pager li {
  background: transparent !important;
}
.el-pager .number {
  color: #00d8f5 !important;
}
.el-pager .active {
  color: #fff !important;
  background: #1682e6 !important;
}
.btn-prev,
.btn-next {
  background: #1682e6 !important;
  i {
    color: white !important;
  }
}
.el-dialog {
  background: #0a1351;
}
.el-dialog__title {
  color: #1682e6;
}
.el-dialog__header,
.el-dialog__title {
  text-align: left;
  font-weight: bold;
  letter-spacing: 3px;
  font-size: 24px !important;
}
</style>